package cn.sinjet.database;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class SQLlightHelper {

	private final int BUFFER_SIZE = 1024 * 100;
	public static final String PACKAGE_NAME = "com.mgroup.wazehelper";
	public static final String DB_PATH = "/data"
			+ Environment.getDataDirectory().getAbsolutePath() + "/"
			+ PACKAGE_NAME;

	private SQLiteDatabase database;
	private Context context;

	public SQLlightHelper(Context context) {
		this.context = context;
	}

	public SQLiteDatabase openDatabase(String dbName) {
		dbName = DB_PATH + "/" + dbName;
		database = SQLiteDatabase.openOrCreateDatabase(dbName, null);
		return database;
	}

	public boolean delete(String dbName) {
		closeDatabase();
		String dbNameTmp = DB_PATH + "/" + dbName;
		File f = new File(dbNameTmp);
		if (f.exists()) {
			return f.delete();
		}
		return false;
	}

	public SQLiteDatabase openDatabase(String dbName, int copyResDBId) {
		try {
			String dbNameTmp = DB_PATH + "/" + dbName;
			if (!(new File(dbNameTmp).exists())) {
				InputStream is = this.context.getResources().openRawResource(
						copyResDBId);
				FileOutputStream fos = new FileOutputStream(dbNameTmp);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			return openDatabase(dbName);
		} catch (FileNotFoundException e) {
			Log.e("openDatabase()", "File not found");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("openDatabase()", "IO exception");
			e.printStackTrace();
		}
		return null;
	}

	public void closeDatabase() {
		if (database != null) {
			database.close();
			database = null;
		}
	}
}
